<template>
  <div class="delivery-admin-dashboard">
    <el-main>
      <h1>配送管理员工作台</h1>
      
      <!-- 统计卡片 -->
      <el-row :gutter="20" class="stat-cards">
        <el-col :span="6">
          <el-card class="stat-card">
            <template #header>
              <div class="card-header">
                <span>已分配任务</span>
              </div>
            </template>
            <div class="stat-value">{{ stats.pendingTasks }}</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <template #header>
              <div class="card-header">
                <span>配送中任务</span>
              </div>
            </template>
            <div class="stat-value">{{ stats.deliveringTasks }}</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <template #header>
              <div class="card-header">
                <span>今日完成</span>
              </div>
            </template>
            <div class="stat-value">{{ stats.completedToday }}</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <template #header>
              <div class="card-header">
                <span>活跃配送员</span>
              </div>
            </template>
            <div class="stat-value">{{ stats.activeDeliverymen }}</div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 图表行 -->
      <el-row :gutter="20" class="chart-row">
        <!-- 任务状态分布图表 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>任务状态分布</span>
              </div>
            </template>
            <div id="task-status-chart" style="height: 400px;"></div>
          </el-card>
        </el-col>

        <!-- 区域配送量图表 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>区域配送量</span>
              </div>
            </template>
            <div id="area-delivery-chart" style="height: 400px;"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 紧急任务列表 -->
      <el-card class="urgent-tasks-card">
        <template #header>
          <div class="card-header">
            <span>紧急任务</span>
            <el-button 
              type="success" 
              size="small" 
              :style="{ backgroundColor: '#0f9b0f', borderColor: '#0f9b0f' }" 
              @click="goToTasksPage"
            >查看全部</el-button>
          </div>
        </template>
        <el-table :data="urgentTasks" style="width: 100%">
          <el-table-column prop="delivery_number" label="配送编号" width="120" />
          <el-table-column prop="order_number" label="订单编号" width="120" />
          <el-table-column prop="customer_name" label="客户名称" width="120" />
          <el-table-column prop="address" label="配送地址" min-width="200" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag type="danger">{{ getStatusText(row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="{ row }">
              <el-button 
                type="success" 
                link 
                :style="{ color: '#0f9b0f' }"
                @click="handleAssign(row)"
              >立即分配</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-main>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import { getDashboardStats } from '@/api/dashboard'
import axios from 'axios' // 确保导入axios
import { getToken } from '@/utils/auth'

const router = useRouter()

// 调试变量
const showDebugInfo = ref(true) // 默认显示调试信息
const rawData = ref({}) // 存储原始数据

// 新增：配送任务API调试相关变量
const deliveryTasksData = ref({}) // 存储配送任务API响应数据
const deliveryTasksLoading = ref(false) // 加载状态

// 统计数据
const stats = reactive({
  pendingTasks: 0,
  deliveringTasks: 0,
  completedToday: 0,
  activeDeliverymen: 0
})

// 紧急任务列表
const urgentTasks = ref([])

// 图表实例
let taskStatusChart = null
let areaDeliveryChart = null

// 获取仪表盘数据 - 只获取今日完成和活跃配送员数据
const fetchDashboardData = async () => {
  try {
    console.log('开始获取仪表盘数据')
    
    const response = await getDashboardStats()
    console.log('仪表盘数据响应完整对象:', response)
    
    // 保存原始数据用于调试显示
    rawData.value = response
    
    // 后端直接返回数据，不需要再取response.data
    const data = response
    
    // 只使用后端返回的今日完成和活跃配送员数据
    stats.completedToday = data.completed_today || 0
    stats.activeDeliverymen = data.active_deliverymen || 0
    
    // 更新紧急任务列表
    urgentTasks.value = data.urgent_tasks || []
    
    // 不再使用后端返回的任何图表数据，将在fetchAllDeliveryTasks中计算
  } catch (error) {
    console.error('获取仪表盘数据失败:', error)
    ElMessage.error('获取仪表盘数据失败: ' + (error.message || '未知错误'))
  }
}

// 初始化任务状态分布图表 - 使用前端计算的数据
const initTaskStatusChart = (data) => {
  try {
    console.log('初始化任务状态图表，数据:', data)
    if (!taskStatusChart) {
      taskStatusChart = echarts.init(document.getElementById('task-status-chart'))
    }
    
    const colorList = [
      {
        color: { type: 'linear', x: 0, y: 0, x2: 1, y2: 1, colorStops: [ { offset: 0, color: '#43e97b' }, { offset: 1, color: '#38f9d7' } ] },
        shadow: 'rgba(67,233,123,0.3)'
      },
      {
        color: { type: 'linear', x: 0, y: 0, x2: 1, y2: 1, colorStops: [ { offset: 0, color: '#00b09b' }, { offset: 1, color: '#96c93d' } ] },
        shadow: 'rgba(0,176,155,0.3)'
      },
      {
        color: { type: 'linear', x: 0, y: 0, x2: 1, y2: 1, colorStops: [ { offset: 0, color: '#02aab0' }, { offset: 1, color: '#00cdac' } ] },
        shadow: 'rgba(2,170,176,0.3)'
      },
      {
        color: { type: 'linear', x: 0, y: 0, x2: 1, y2: 1, colorStops: [ { offset: 0, color: '#11998e' }, { offset: 1, color: '#38ef7d' } ] },
        shadow: 'rgba(17,153,142,0.3)'
      },
      {
        color: { type: 'linear', x: 0, y: 0, x2: 1, y2: 1, colorStops: [ { offset: 0, color: '#0f9b0f' }, { offset: 1, color: '#45b649' } ] },
        shadow: 'rgba(15,155,15,0.3)'
      }
    ]
    const names = ['待处理', '已分配', '配送中', '已完成', '已取消']
    const values = [data.pending || 0, data.assigned || 0, data.delivering || 0, data.completed || 0, data.cancelled || 0]
    const option = {
      tooltip: {
        trigger: 'item',
        backgroundColor: '#fff',
        borderColor: '#eee',
        textStyle: { color: '#333' },
        formatter: p => `${p.marker} <b>${p.name}</b><br/>数量: <b>${p.value}</b><br/>占比: <b>${p.percent}%</b>`
      },
      legend: {
        orient: 'vertical',
        right: '5%',
        top: 'middle',
        icon: 'circle',
        itemWidth: 16,
        itemHeight: 16,
        itemGap: 16,
        textStyle: { 
          fontSize: 14, 
          color: '#333',
          padding: [0, 0, 0, 4]  // 文字和图标的间距
        },
        data: names
      },
      series: [
        {
          name: '任务状态',
          type: 'pie',
          radius: ['45%', '70%'],
          center: ['40%', '50%'],  // 将饼图向左移动，为图例腾出空间
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 12,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: true,
            position: 'outside',
            color: '#333',
            fontSize: 14,
            formatter: '{b}\n{d}%',
            fontWeight: 'bold'
          },
          labelLine: {
            show: true,
            length: 18,
            length2: 12,
            lineStyle: { color: '#333', width: 1.5 }
          },
          data: names.map((name, i) => ({
            value: values[i],
            name,
            itemStyle: {
              color: colorList[i].color,
              shadowBlur: 20,
              shadowColor: colorList[i].shadow
            }
          })),
          emphasis: {
            scale: true,
            scaleSize: 12,
            itemStyle: {
              shadowBlur: 40,
              shadowColor: 'rgba(0,0,0,0.25)'
            }
          },
          animation: true,
          animationEasing: 'cubicOut',
          animationDuration: 1200
        }
      ]
    }
    
    taskStatusChart.setOption(option)
    console.log('任务状态图表初始化完成')
  } catch (error) {
    console.error('初始化任务状态图表失败:', error)
  }
}

// 初始化区域配送量图表 - 使用前端计算的数据
const initAreaDeliveryChart = (data) => {
  try {
    console.log('初始化区域配送图表，数据:', data)
    if (!areaDeliveryChart) {
      areaDeliveryChart = echarts.init(document.getElementById('area-delivery-chart'))
    }

    const areaNames = Object.keys(data);
    const areaValues = Object.values(data);
    console.log('区域名称:', areaNames)
    console.log('区域值:', areaValues)

    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: [
        {
          type: 'category',
          data: areaNames,
          axisTick: {
            alignWithLabel: true
          },
          axisLine: {
            lineStyle: {
              color: '#333'
            }
          },
          axisLabel: {
            color: '#333'
          }
        }
      ],
      yAxis: [
        {
          type: 'value',
          axisLine: {
            lineStyle: {
              color: '#333'
            }
          },
          axisLabel: {
            color: '#333'
          }
        }
      ],
      series: [
        {
          name: '配送量',
          type: 'bar',
          barWidth: '60%',
          data: areaValues,
          itemStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                {
                  offset: 0,
                  color: '#00b09b'  // 深青绿色
                },
                {
                  offset: 1,
                  color: '#0f9b0f'  // 深绿色
                }
              ]
            },
            borderRadius: [5, 5, 0, 0]  // 柱状图顶部圆角
          },
          emphasis: {
            itemStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: '#02aab0'  // hover时的深青色
                  },
                  {
                    offset: 1,
                    color: '#11998e'  // hover时的深绿色
                  }
                ]
              }
            }
          },
          label: {
            show: true,
            position: 'top',
            color: '#333',
            fontWeight: 'bold',
            formatter: '{c} 单'
          }
        }
      ]
    }
    areaDeliveryChart.setOption(option)
    console.log('区域配送图表初始化完成')
  } catch (error) {
    console.error('初始化区域配送图表失败:', error)
  }
}

// 获取所有配送任务并计算所有统计数据
const fetchAllDeliveryTasks = async () => {
  deliveryTasksLoading.value = true
  try {
    // 使用 auth.js 中的 getToken 函数获取 token
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录获取token')
      deliveryTasksLoading.value = false
      return
    }
    
    // 直接调用后端API
    const response = await axios.get('/api/delivery-tasks/', {
      headers: {
        'Authorization': `Bearer ${token}`
      },
      params: {
        // 可选：添加分页参数
        page: 1,
        page_size: 100 // 获取较多数据以便查看
      }
    })
    
    // 保存响应数据
    deliveryTasksData.value = response.data
    console.log('配送任务API响应:', response.data)
    
    // 如果请求成功但没有获取到预期格式的数据，给出提示
    if (!response.data || !response.data.data || !response.data.data.items) {
      console.warn('API响应格式可能不符合预期:', response.data)
    } else {
      const tasks = response.data.data.items;
      
      // 计算各状态任务数量
      const pendingTasks = tasks.filter(task => task.status === 'pending').length
      const assignedTasks = tasks.filter(task => task.status === 'assigned').length
      const deliveringTasks = tasks.filter(task => task.status === 'delivering').length
      const completedTasks = tasks.filter(task => task.status === 'completed').length
      const cancelledTasks = tasks.filter(task => task.status === 'cancelled').length
      
      // 更新统计数据 - 待分配任务包括pending和assigned状态
      stats.pendingTasks = pendingTasks + assignedTasks
      stats.deliveringTasks = deliveringTasks
      
      console.log('计算得到的待处理任务数量:', pendingTasks)
      console.log('计算得到的已分配任务数量:', assignedTasks)
      console.log('计算得到的配送中任务数量:', deliveringTasks)
      
      // 初始化任务状态分布图表
      initTaskStatusChart({
        pending: pendingTasks,
        assigned: assignedTasks,
        delivering: deliveringTasks,
        completed: completedTasks,
        cancelled: cancelledTasks
      })
      
      // 计算区域配送量（从address字段提取"区"）
      const areaDeliveryDistribution = {};
      tasks.forEach(task => {
        if (task.address) {
          // 匹配"xx区"或"xx县"或"xx市"或"xx镇"
          const match = task.address.match(/([\u4e00-\u9fa5]{2,10}(区|县|市|镇))/);
          const areaName = match ? match[1] : '未知区域';
          if (!areaDeliveryDistribution[areaName]) {
            areaDeliveryDistribution[areaName] = 0;
          }
          areaDeliveryDistribution[areaName]++;
        }
      });
      console.log('计算得到的区域配送量:', areaDeliveryDistribution);
      // 初始化区域配送量图表
      initAreaDeliveryChart(areaDeliveryDistribution);
    }
    
    ElMessage.success('获取配送任务数据成功')
  } catch (error) {
    console.error('获取配送任务数据失败:', error)
    if (error.response) {
      console.error('错误响应状态码:', error.response.status)
      console.error('错误响应数据:', error.response.data)
      deliveryTasksData.value = { error: error.response.data, status: error.response.status }
    } else {
      deliveryTasksData.value = { error: error.message }
    }
    ElMessage.error('获取配送任务数据失败: ' + (error.message || '未知错误'))
  } finally {
    deliveryTasksLoading.value = false
  }
}

onMounted(() => {
  console.log('组件挂载完成，开始获取数据')
  fetchDashboardData()
  fetchAllDeliveryTasks() // 确保这行代码被执行
  
  // 窗口大小变化时重绘图表
  window.addEventListener('resize', () => {
    taskStatusChart && taskStatusChart.resize()
    areaDeliveryChart && areaDeliveryChart.resize()
  })
})

// 确保已经定义了navigateTo函数
const navigateTo = (path) => {
  router.push(path)
}

// 处理分配任务
const handleAssign = (task) => {
  console.log('分配任务:', task)
  router.push({
    path: '/delivery_admin/tasks',
    query: { task_id: task.id }
  })
}

// 跳转到任务页面
const goToTasksPage = () => {
  router.push('/delivery_admin/tasks')
}

// 获取状态样式 - 与DeliveryManagement.vue保持一致
const getStatusType = (status) => {
  const statusMap = {
    'pending': 'warning',
    'assigned': 'info',
    'delivering': 'primary',
    'completed': 'success',
    'cancelled': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本 - 与DeliveryManagement.vue保持一致
const getStatusText = (status) => {
  const statusMap = {
    'pending': '待处理',
    'assigned': '已分配',
    'delivering': '配送中',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return statusMap[status] || status
}
</script>

<style scoped>
.delivery-admin-dashboard {
  height: 100%;
  width: 100%;
}

.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  height: 160px;
  padding: 15px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.stat-value {
  font-size: 28px;  /* 统一数字大小 */
  font-weight: bold;
  text-align: center;
  margin-top: 10px;
  color: #0f9b0f;  /* 统一使用深绿色 */
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  height: 100%;
}

.chart-card :deep(.el-card__header) {
  padding: 15px 20px;
}

.chart-card :deep(.el-card__body) {
  padding: 10px;
  height: calc(100% - 60px);
}

.urgent-tasks-card {
  margin-bottom: 20px;
}

.urgent-tasks-card :deep(.el-card__header) {
  padding: 15px 20px;
}

/* 调试卡片样式 */
.debug-card {
  margin-top: 20px;
  margin-bottom: 20px;
  background-color: #f8f8f8;
}

.debug-card pre {
  font-family: monospace;
  font-size: 14px;
  padding: 10px;
  background-color: #f0f0f0;
  border-radius: 4px;
}

/* 新增：加载指示器样式 */
.loading-indicator {
  text-align: center;
  padding: 20px;
  font-size: 16px;
  color: #909399;
}
</style>